package com.weixx.shiro.config;


import com.weixx.shiro.pojo.User;
import com.weixx.shiro.service.UserServiceImp;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.InvocationTargetException;

//自定义的UserRealm  extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserServiceImp userService;


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了=》doGetAuthorizationInfo 授权");

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //info.addStringPermission("user:update");
        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        Object object = subject.getPrincipal();
        User currentUser = new User();
        try {
            PropertyUtils.copyProperties(currentUser,object);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
        //设置用户权限
        info.addStringPermission(currentUser.getPerms());
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了=》doGetAuthenticationInfo 认证");
        //用户名 密码 数据库取除校验

        UsernamePasswordToken usernamePasswordToken= (UsernamePasswordToken) authenticationToken;
        //链接真实数据库
        User user=userService.queryUserByName(usernamePasswordToken.getUsername());

        if(user==null){
            return  null;//为空默认用户名不对
        }
        //密码认证 ， shiro做
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
